(() => {
  function copyToClipboard(textToCopy) {
    // 1. 获取需要复制的文本内容
    // textToCopy
    // 2. 创建一个临时的 textarea 元素
    const tempInput = document.createElement('textarea');
    tempInput.value = textToCopy;
    document.body.appendChild(tempInput);

    // 3. 选中文本内容
    tempInput.select();
    tempInput.setSelectionRange(0, 99999); // 适用于移动设备

    // 4. 执行复制命令
    document.execCommand('copy');

    // 5. 移除临时 textarea 元素
    document.body.removeChild(tempInput);

    alert(`已复制到剪贴板: ${textToCopy}`);
  }
  window.defineTimmyScript = () => {
    try {
      if (window.timmyTanTimeout) {
        clearInterval(window.timmyTanTimeout);
      }
      // @ts-ignore
      window.timmyTanTimeout = setInterval(() => {
        // let res = localStorage.getItem('timmy_ext_app_search_content');
        const res = '[a-zA-Z_]';
        // if (!res || res.length <= 0) {
        //   res = '[a-zA-Z_]';
        // }
        const avatarSon = document.querySelectorAll(
          '[data-testid="tweetText"]'
        );
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < avatarSon.length; i++) {
          const container = avatarSon[i];
          const isExist = container.parentElement.querySelector(
            `[timmy-tan-test-dom-attr="timmy-tan-ext-1"]`
          );
          if (isExist) {
            // eslint-disable-next-line no-continue
            continue;
          }
          const textContainer = container.textContent || '';
          const regex = new RegExp(`[$#]${res}`, 'i');
          const isBoolean = regex.test(textContainer);
          if (isBoolean) {
            const dollarRegex = /\$([a-zA-Z]+)/g;
            const match = textContainer.match(dollarRegex);
            if (match) {
              const dollarContent = [...new Set(match)].map((item) =>
                item.replace('$', '')
              );
              // eslint-disable-next-line no-plusplus
              const span = document.createElement('span');
              // 设置 img 元素的属性
              span.setAttribute('timmy-tan-test-dom-attr', `timmy-tan-ext-1`); // 设置自定义属性
              span.style.display = 'inline-block';
              span.style.color = 'red';
              span.style.position = 'absolute';
              span.style.top = '0';
              span.style.right = '0';
              span.style.padding = '10px 20px';
              span.style.maxWidth = '220px';
              span.style.zIndex = '11';
              span.style.wordBreak = 'break-word';
              span.style.cursor = 'copy';
              span.style.backgroundColor = '#fff';
              span.textContent = dollarContent.join(',');
              span.addEventListener('click', (event) => {
                event.stopPropagation();
                copyToClipboard(JSON.stringify(dollarContent));
              });
              container.parentElement.appendChild(span);
            }
          }
          // // 将 img 元素添加到容器元素中
        }
      }, 1500);
    } catch (e) {
      // btnStatus.value = false;
      console.log(JSON.stringify(e), 'error nihao');
    }
  };
  window.onload = () => {
    window.defineTimmyScript();
  };
})();
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  try {
    console.log('收到来自content-script的消息：', request);
    const { searchText } =
      typeof request === 'string'
        ? JSON.parse(request.trim().toString())
        : request;
    if (searchText.length > 0) {
      localStorage.setItem('timmy_ext_app_search_content', searchText);
    } else {
      localStorage.removeItem('timmy_ext_app_search_content');
    }
    console.log(request, sender, sendResponse);
    sendResponse(`我是后台，我已收到你的消息：${JSON.stringify(request)}`);
  } catch (e) {
    console.log(e);
  }
});
